package com.superb.common.utils;

import com.superb.common.core.enums.EncryptType;
import org.apache.commons.lang3.StringUtils;

/**
 * 脱敏工具类
 *
 * @Author: ajie
 * @CreateTime: 2024-05-13 17:46
 */
public class DesensitizedUtils {

    /**
     * 脱敏
     * @param content
     * @param type
     * @return
     */
    public static String desensitized(String content, EncryptType type) {
        return switch (type) {
            case PHONE -> desensitizedPhone(content);
            case EMAIL -> desensitizedEmail(content);
            case IDCARD, CREDITCODE -> desensitizedIdcard(content);
            case BANKCARD -> desensitizedBankcard(content);
            case REALNAME -> desensitizedName(content);
            case ADDRESS -> desensitizedAddress(content);
            default -> content;
        };
    }

    private static String desensitizedEmail(String email) {
        int index = email.indexOf("@");
        if (index <= 2) {
            return email;
        }
        return email.substring(0, 2) + "****" + email.substring(index);
    }

    /**
     * 手机号脱敏
     *
     * @param phone
     * @return
     */
    private static String desensitizedPhone(String phone) {
        return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }

    /**
     * 身份证号脱敏
     *
     * @param idcard
     * @return
     */
    private static String desensitizedIdcard(String idcard) {
        return idcard.replaceAll("^(.{6})(.{8})(.*)$", "$1********$3");
    }

    /**
     * 银行卡号脱敏
     *
     * @param bankCard
     * @return
     */
    private static String desensitizedBankcard(String bankCard) {
        return bankCard.replaceAll("(\\d{6})\\d{9}(\\d{4})", "$1****$2");
    }

    /**
     * 姓名脱敏
     *
     * @param content
     * @return
     */
    private static String desensitizedName(String content) {
        String left = StringUtils.left(content, 1);
        int length = StringUtils.length(content);
        if (length == 1) {
            return left;
        } else if (length == 4) {
            left = StringUtils.left(content, 2);
        }
        return StringUtils.rightPad(left, length, "*");
    }

    /**
     * 姓名脱敏
     *
     * @param content
     * @return
     */
    private static String desensitizedAddress(String content) {
        String left = StringUtils.left(content, 1);
        return StringUtils.rightPad(left, StringUtils.length(content), "*");
    }
}
